;(function(global) {
	var CGI = {
		GET_PLAYS 			: function (){ return window.frontPath + 'lottery/play?r=' + new Date().getTime()},
		LOTTERY_TIME 		: function (){ return window.frontPath + 'lottery/currenttime?r=' + new Date().getTime()},	//获取倒计时时间
		SUBMIT_CODES		: function (){ return window.frontPath + 'lottery/submit?r=' + new Date().getTime()},
		LOTTERY_HISTORY		: function (){ return window.frontPath + 'lottery/history?r=' + new Date().getTime()}, 		//获取最近十期投彩记录
		LOTTERY_DISTANCE	: function (){ return window.frontPath + 'lottery/distance?r=' + new Date().getTime()},		//判断当前时间是否在开奖间隔时间之内
		LOTTERY_APPENDBET	: function (){ return window.frontPath+ 'lottery/appendbet?r=' + new Date().getTime()},		//查询追号
		CANCEL_ORDER		: function (){ return window.frontPath + 'lottery/cancelLotteryBets?r=' + new Date().getTime()},//撤单
		LOTTERY_OPEN_DATA	: function (){ return window.frontPath + 'lottery/opendata?r=' + new Date().getTime()},		//是否开奖，未开奖是0 已开奖是开奖数据
		LOTTERY_BET_DETAIL	: function (){ return window.frontPath + 'lottery_bets/detail?r=' + new Date().getTime()},		//是否开奖，未开奖是0 已开奖是开奖数据
		LOTTERY_HISTORY_DATA: function (){ return window.frontPath + 'lottery/queryHistoryLotteryData?r=' + new Date().getTime()}		//查询历史开奖记录
	};

	var play_arr 		= []; 	// 存储当前玩法组所有的玩法

	var curr_play_obj 	= null; // 存储当前玩法组的当前玩法

	var fandian			= (+$('#user_fandian').val()) * 100;	//从用户信息中取出的返点信息(等比例计算)
	
	global.Play = {
		/**
		 * 创建自定义单号
		 * @return {[type]} [description]
		 */
		createCustomOrderNo : function (){
			return ""+Math.round((Math.random() * 1000000))+
				new Date().getTime()+Math.round((Math.random() * 10000000));
		},
		/**
		 * 奖金计算
		 * 奖金=最高奖金*(元[1]，角[0.1],分[0.01]})-(13%-个人返点数)*模式(元[2]，角[0.2],分[0.02]})*总注数
		 */
		bonusCalc : function (_maxBonus , _fd , _totalZhu){
			return (_maxBonus * 1 - (_fd) * 2 * _totalZhu).toFixed(2);
		},
		/**
		 * 倒计时公共函数
		 * @param {Date}	_currDate 服务器当前时间
		 * @param {Object} _diff 倒计时终结点
		 * @param {Function} _doFunc 正在倒计时的监听事件
		 * @param {Function} _callBack 倒计时完成回调事件
		 * @return {[type]}       [description]
		 */
		initDownTime : function ( _currDate , _diff ,_doFunc ){
			$('#countdown_dashboard').stopCountDown();
			$('#countdown_dashboard').countDown({
				nowTime	:	_currDate,
				doFunc	: _doFunc,
				targetDate: {
					'day'	: 	_diff.day,
					'month'	: 	_diff.month,
					'year'	: 	_diff.year,
					'hour'	: 	_diff.hour,
					'min'	: 	_diff.min,
					'sec'	: 	_diff.sec					
				}
			});
		},
		/**
		 * 右侧按钮控制
		 */
		rightBtn : function() {
			$("#delegate-content").delegate(
					'.game-xhlist-right input', 'click',
				function() {
					var _jq_rbtn_parent	=$(this).parents('.game-xhlist-right');
					_jq_rbtn_parent.find('.game-rbtn').removeClass('game-rbtn-active');
					$(this).addClass('game-rbtn-active');
					var _jq_digital = _jq_rbtn_parent.prev('.game-xhlist-left').find('.game-lbtn');
					_jq_digital.removeClass('game-lbtn-active');
					var _flag = $(this).attr('data-flag') || '';
					switch (_flag) {
					case 'qing': // 清
						break;

					case 'shuang': // 双
						_jq_digital.each(function(index, domEle) {
							var _val = +$(domEle).val();
							if (_val % 2 == 0) {
								$(domEle).addClass('game-lbtn-active');
							}
						});
						break;

					case 'dan': // 单
						_jq_digital.each(function(index, domEle) {
							var _val = +$(domEle).val();
							if (_val % 2 == 1) {
								$(domEle).addClass('game-lbtn-active');
							}
						});
						break;

					case 'xiao': // 小
						var _digitalLen = _jq_digital.length;
						var _middle = Math.round(_digitalLen / 2);
						_jq_digital.each(function(index, domEle) {
							var _val = +$(domEle).val();
							if (_middle > _val) {
								$(domEle).addClass('game-lbtn-active');
							}
						});
						break;

					case 'da': // 大
						var _digitalLen = _jq_digital.length;
						var _middle = Math.round(_digitalLen / 2);
						_jq_digital.each(function(index, domEle) {
							var _val = +$(domEle).val();
							if (_middle <= _val) {
								$(domEle).addClass('game-lbtn-active');
							}
						});
						break;

					case 'quan': // 全
						_jq_digital.addClass('game-lbtn-active');
						break;
					}
					Play.getNumAndDetail();
				});
		},
		/**
		 * 拼装投注数字
		 */
		assemble : function() {
			var _totalArr = [];
			$('.game-xhlist-left').each(
				function(index, domEle) {
					var _trArr = [];
					$(domEle).find('.game-lbtn-active').each(
							function(posIdx, posEle) {
								_trArr.push($(posEle).val());
							});
					_totalArr.push(_trArr);
				});
			return _totalArr;
		},
		/**
		 * 获取投注总数和投注详情
		 */
		getNumAndDetail : function(evt , isDel) {
			var _conf = playsConf(curr_play_obj);
			Play.slider();
			//如果用户正在按删除键，就启用另一套算法
			var _num = 0;
			if(isDel){
				_num = SSC.DAN_DEL.apply(null, _conf['param']);
			}else{
				_num = _conf['algo'].apply(null, _conf['param']);
			}
			if(isNaN(_num)){
				if(/.*[\u4e00-\u9fa5]+.*$/.test(_num)){
					$('#touzhuInfo').html('<h2><em id="zhu">'+ _num +'</em></h2>');
				}else{
					$('#touzhuInfo').html('<h2>共<em id="zhu">0</em>注，金额<em id="money">0.00</em>元</h2>');
				}
				return null;
			}
			$('#touzhuInfo').html('<h2>共<em id="zhu">0</em>注，金额<em id="money">0.00</em>元</h2>');
			var _detail = _conf['detail'];
			var _model = +$('input[name="model"]:checked').val();
			var _times = +$('.pro-qty-int').val();
			var _money = (_num * _model * _times).toFixed(2);
			$('#zhu').html(_num);
			$('#money').html(_money);
		},
		/**
		 * 获取方案
		 */
		getPlan : function (_n){
			var _posLen = $('input[name="position"]:checked').length;
			$('#positioncount').html(_posLen);
			if(_posLen == 0){
				$('#positioninfo').html(0);
			}else{
				$('#positioninfo').html(Math.Com(_posLen , _n));
			}
		},
		
		/**
		 * 数字复位
		 */
		reset : function (){
			$('#game-input').val('');Play.slider();	//同步滑块数值
			$('.game-xhlist-left .game-lbtn-active').removeClass('game-lbtn-active');
			$('.game-xhlist-right .game-rbtn-active').removeClass('game-rbtn-active');
			$('#touzhuInfo').html('<h2>共<em id="zhu">0</em>注，金额<em id="money">0.00</em>元</h2>');
		},
		/**
		 * 解析投注数字,解析成购物车认识的格式
		 */
		parsing : function (){
			var _zhuStr = '';
			var _conf = playsConf(curr_play_obj);
			var _type = _conf['type'];
			if('digital' == _type){	//数字选择型的解析方式
				var xhlistLen = $('#game-panel .game-xhlist-left').length;
				$('#game-panel .game-xhlist-left').each(function (index, domEle){
					if(curr_play_obj['ruleFun'] === '2xz_rx2zxfs'){	//任二 组选复式
						var pos_num_arr = [];
						$(domEle).
						find('.game-lbtn.game-lbtn-active').
						each(function (sub_i , sub_d){
							pos_num_arr.push($(sub_d).val());
						});
						_zhuStr = pos_num_arr.join('');
					}else {
						var activeLen = $(domEle).find('.game-lbtn.game-lbtn-active').length;
						$(domEle).
						find('.game-lbtn.game-lbtn-active').
						each(function (sub_i , sub_d){
							if(sub_i < ($(domEle).find('.game-lbtn.game-lbtn-active').length-1) ){
								_zhuStr += $(sub_d).val() + ' ';
							}else{
								_zhuStr += $(sub_d).val();
							}
						});
						if(index < (xhlistLen-1) && activeLen > 0){
							_zhuStr += ',';
						}
						//如果当前位没有数字，就用*代替
						if(index < (xhlistLen-1) && activeLen === 0){
							_zhuStr += '*,';
						}else if(index >= (xhlistLen-1) && activeLen === 0){
							_zhuStr += '*';
						}
					}
				});
				_zhuStr = _zhuStr.replace(/,$/,'');
			}else 
			if('input' == _type){	//手动输入型的解析方式
				var _pri_zhuStr = '';
				if(_conf.fRegular){
					_pri_zhuStr = $('#game-input').val().replace(_conf.fRegular , '|');
				}else{
					_pri_zhuStr = $('#game-input').val().replace(/\s{1}/g , '|');
				}
				_pri_zhuStr = _pri_zhuStr.replace(/\|$/ , '');
				_zhuStr = _pri_zhuStr;
			}
			return _zhuStr;
		},
		/**
		 * 购物车接收函数
		 */
		cart : function (_cart_obj){
			if(!_cart_obj.playName){
				$.alert({
					status     : 'error',
					basicTitle : '亲，名称不能为空哦！'
				});
				return;
			}
			if(!_cart_obj.zhu){
				$.alert({
					status     : 'error',
					basicTitle : '亲，投注数不能为0哈！'
				});
				return;
			} 		
			if(_cart_obj.total == "0" || 
				_cart_obj.money == "0.00" ||
				!/^\d+$/.test(_cart_obj.total)){
				$.alert({
					status     : 'error',
					basicTitle : '亲，请先下注哦！'
				});
				return;
			}

			if( (+curr_play_obj['maxCount']) < (+_cart_obj.total) ){
				$.alert({
					status     : 'error',
					basicTitle : '不能超过最大投注数：'+curr_play_obj['maxCount'] + '注'
				});
				return;
			}

			var maxJiangJin = 100000;
			//奖金 * 倍数 > 设置的最大中奖金额 
			var _model = $('input[name="model"]:checked').val();
			var _m	   = 0.01;
			if('2.00' == _model){
				_m = 1;
			}else 
			if('0.20' == _model){
				_m = 0.1;
			}else 
			if('0.02' == _model){
				_m = 0.01;
			}
			var isDaYuBonus = (+$('#playBonus').html()*_m) * 
				(+$('.pro-qty-int').val()) > maxJiangJin ? true : false;
			if( isDaYuBonus ){
				$.alert({
					status     : 'error',
					basicTitle : '不能超过最高中奖金额：￥'+maxJiangJin
				});
				return;
			}
			if(!_cart_obj.times){
				$.alert({
					status     : 'error',
					basicTitle : '亲，没有倍数。'
				});
				return;
			}
			if(!_cart_obj.model){
				$.alert({
					status     : 'error',
					basicTitle : '亲，没有选择模式。'
				});
				return;
			}
			if(!_cart_obj.bonus){
				$.alert({
					status     : 'error',
					basicTitle : '亲，没有中奖金额。'
				});
				return;
			}
			//将原始数据备份起来
			_cart_obj['zhu_original'] = _cart_obj.zhu;
			//注数长度超过11位就自动用...隐藏
			_cart_obj.zhu = _cart_obj.zhu.replace(/^(.{11})(.*)$/,function (){
				var _param = [].slice.apply(arguments); 
				if(_param[2].length > 0){
					return _param[1]+'...';
				}
				return _param[1];
			});
			
			_cart_obj['lotteryNo'] = $('[data-id="sale-nper"]').html();
			//将“暂时没数据”的提示干掉
			$('#cart-list tr[data-flag="empty"]').remove();
			var _htmlStr = _.template($('#cart-template').html() , _cart_obj);
			$('#cart-list').prepend(_htmlStr);
			$('#cart-list tr').fadeIn();
			this.cartMonitor();
		},
		/**
		 * 购物车监控 如增减号码 会影响购物车总注数、总金额以及行样式的变动
		 */
		cartMonitor : function (){
			var _zhu_total = 0;
			$('#cart-list [data-flag="total"]').each(function (index,zhuEle){
				_zhu_total += +($(zhuEle).val());
			});
			var _money_total = 0;
			$('#cart-list [data-flag="money"]').each(function (index,moneyEle){
				_money_total += +($(moneyEle).val());
			});
			$('#cart-total-zhu').html(_zhu_total);
			$('#cart-total-money').html(_money_total.toFixed(2));
			$('#cart-list tr').removeClass('alt');
			$('#cart-list tr:odd').addClass('alt');
			if($('#cart-list tr').length > 4){
				$('#cart-area').addClass('content-jv');
			}else{
				$('#cart-area').removeClass('content-jv');
			}
		},
		/**
		 * 购物车数据
		 */
		cartData : function (){
			var _data = [];
			$('#cart-list tr[data-flag!="empty"]').each(function (index , ele){
				var ids = $(ele).find('[data-flag="id"]').val().split('-');
				_data.push({
					betsIdentification : $(ele).attr('data-orderNo'),		//投注的唯一标识
					betsSrcIdent	   : $(ele).attr('sub_orderNo') || '',	//主单号的唯一标识
					betsData : $(ele).find('[data-flag="zhu"]').val(),
					playName : $(ele).find('[data-flag="playName"]').val(),
					betsNum : parseInt($(ele).find('[data-flag="total"]').val()),
					betsAmount : parseFloat($(ele).find('[data-flag="money"]').val()),
					betsBeishu : parseInt($(ele).find('[data-flag="times"]').val()),
					betsMode : parseFloat($(ele).find('[data-flag="model"]').val()),
					betsBonusprop : parseFloat($(ele).find('[data-flag="bonus_c"]').val()),
					betsFandian: parseFloat($(ele).find('[data-flag="fandian"]').val()),
					lotteryPlaygroupid: parseInt(ids[0]),
					lotteryPlayid: parseInt(ids[1]),
					lotteryId: parseInt($('#lottery-id').val()),
					lotteryNo: $(ele).find('[data-flag="lotteryNo"]').val(),
					lotteryType: $('#lottery-type').val(),
					betsZhuihao: parseInt($('.lotteryNo', ele).attr('bets_zhuiHao')),
					betsZhuihaomode: parseInt($('.lotteryNo', ele).attr('bets_zhuiHaoMode')),
					betsWeishu : $(ele).attr('data-fangAn')
				});
			});
			
			return _data;
		},
		/**
		 * 滑块方法
		 */
		slider : function (){
			window.setTimeout(function (){
				var _currVal = +$("#blue").slider('value').toFixed(2);
				$('#playBonus').html(Play.bonusCalc(
						(+curr_play_obj['bonusProp'] - (0.13 - 
							(+$('#user_fandian').val())) * 
						(+curr_play_obj['totalNumber']) * 2 ), 
						((_currVal)/ 100), 
						+curr_play_obj['totalNumber'])
				);
				$('#playBonusPercent').html(_currVal.toFixed(2) + '%');
			},0);
		},
		
		/**
		 * show
		 */
		prize  : {
			/**
			 * 为开奖和停止售奖添加音效功能
			 * @param src			//音效地址
			 * @param domId			//音效元素id
			 */
			playVoice : function (src, domId){
				var $dom=$('#'+domId);
				if("0" === $.cookie('LH_02_MUSIC_VOICE')){
					$dom.remove();
				}else{
					if(navigator.userAgent.indexOf('MSIE') >= 0 && 
						!(/Trident\/7\./).test(navigator.userAgent)){
				        if($dom.length){
				            $dom[0].src=src;
				        }else{
				            $('<bgsound>',{src:src, id:domId}).appendTo('body');
				        }
				    }else{
				        if($dom.length){
				            $dom[0].play();
				        }else{
				            $('<audio>',{src:src, id:domId}).appendTo('body')[0].play();
				        }
				    }
				}
			},
			//判断当前时间是否在开奖间隔时间之内
			isTimeDistance : function (isInit){
				var _this = this;
				var deferred = $.Deferred();
				$.ajax({
					url 	: CGI.LOTTERY_DISTANCE(),
					method 	: 'GET',
					data 	: "lotteryId="+$('#lottery-id').val(),
					success : function(data){
						var _diff = 0;
						//如果是在间隔时间内
						if (0 == data.retcode && data.data.length > 0) {
							var _data = data.data[0];
							$('#opening').removeClass('hide');
							$('#open-result').addClass('hide');
							$('.game-result').css({'background-color' : '#F8F8E4'});
							_diff = (+_data.datediff);
							_diff = _diff <10 ? ('0' + _diff) : _diff;
							$('#diff').html('剩余'+_diff + "秒");
						}
						var wait_timer_func = function (){
							if(_diff <= 0){
								clearInterval($.data(
									$('#lottery-data')[0], 
									'wait_timer'
								));
								clearTimeout($.data(
									$('.kj-hao')[0] , 
									'kaijiang_timer'
								));
								$('#diff').html('');
								if(!isInit){
									_this.engine(function (_obj){
										_this.
										queryLotteryOpenDataInfo(
											_obj , 
											20 , 
											false
										);//modify 20
									});
								}else{
									_this.
									engine(function (_obj){
										_this.
										queryLotteryOpenDataInfo(
											_obj,
											5, 
											true
										); //modify 5 
									});
								}
								return false;
							}else{
								_diff--;
								_diff = _diff <10 ? ('0' + _diff) : _diff;
								$('#diff').html('剩余'+_diff + "秒");
								return true;
							}
						};
						//是否往后执行定时器
						var isNextTimer = wait_timer_func();
						if(isNextTimer){
							$.data($('#lottery-data')[0], 'wait_timer', 
								setInterval(wait_timer_func,1000));
						}
					}
				});
				return deferred.promise(); // 返回promise对象
			},
			/**
			 * 开奖失败布局
			 * @return {[type]} [description]
			 */
			lottertyOpenDataFailureStyle : function (){
				$('#opening').addClass('hide');
				$('#open-result').removeClass('hide');
				$('.game-result').css({'background-color' : ''});
				var _lotteryType = $('#lottery-type').val();
				if('PK10' === _lotteryType){
					$('.kj-hao').html($('#pk10-kaijiang-template').html());
				}else{
					$('.kj-hao').html($('#kaijiang-template').html());
				}
			},
			/**
			 * 获取开奖数据
			 * @param  {[type]} _obj       彩种等数据
			 * @param  {[type]} loopScope  load开奖数据的循环次数，超过这个次数不管有没有Load都视为开奖失败
			 * @param {[type]} isInit 是否是初始化时去load的开奖数据
			 * 
			 * @return {[type]}            [description]
			 */
			queryLotteryOpenDataInfo : function (_obj , loopScope ,isInit){
				var _this = this;
				var count =0;
				var kaiJianFunc = function (){
					var _url = $.substitute('{basePath}opendata/{lotteryId}/{lotteryId}_{lotteryNum}.html?r={currTime}' , {
						basePath : window.basePath,
						lotteryId: _obj.lottery_id,
						lotteryNum: _this.getPrevLottery(_obj),	//获取上一期期数
						currTime : new Date().getTime()
					});
					$('.kj-hao').load(_url , function (response , status , xhr){
					    if(!isNaN(xhr.status)){
					    	var _status = +xhr.status;
							//得到上一期的期数
							$('#prev-lottery').html(_this.getPrevLottery(_obj));
							//****** 北京PK10开奖布局 兼容IE8 start***
							var pk10_kaiJiang_layout = function (){
								if(navigator.userAgent.indexOf("MSIE 8")>0){
									var _clientWidth = +document.body.clientWidth;
									if(_clientWidth >= 1000 && _clientWidth < 1200){
										$('.kj-hao li.gr_s').css({'margin-right' : '10px'});
										$('.kj-hao li.gr_s_a').css({'margin-right' : '10px'});
										$('.kj-hao li.gr_s_b').css({'margin-right' : '10px'});
									}else if(_clientWidth >= 1200){
										$('.kj-hao li.gr_s').css({'margin-right' : '20px'});
										$('.kj-hao li.gr_s_a').css({'margin-right' : '20px'});
										$('.kj-hao li.gr_s_b').css({'margin-right' : '20px'});
									}
								}
							};
							$(window).resize(function() {pk10_kaiJiang_layout();});
							pk10_kaiJiang_layout();
							//****** 北京PK10开奖布局 兼容IE8 end***
					    	if(404 === _status){	//没有取到开奖数据
					    		count ++;
					    		clearTimeout($.data($('.kj-hao')[0] , 
					    			'kaijiang_timer'));
					    		if(count >= loopScope){
					    			_this.lottertyOpenDataFailureStyle();
					    		}else{
					    			$('#opening').removeClass('hide');
					    			$('#open-result').addClass('hide');
					    			$('.game-result').css({'background-color' : '#F8F8E4'});
		    			    		//没有取到开奖数据，就等10秒再去拉取
		    			    		$.data($('.kj-hao')[0] , 'kaijiang_timer' , 
		    			    			setTimeout(kaiJianFunc , 10000));
					    		}
					    	}else if(200 === _status){			//取到了开奖数据
					    		$('#opening').addClass('hide');
					    		$('#open-result').removeClass('hide');
					    		$('.game-result').css({'background-color' : ''});
					    		Play.lotteryHistory();
					    		reloadUserInfo();
					    		if(isInit && count === 0) return;
					    		_this.playVoice(window.basePath+'static/media/kai-jiang.mp3' ,
					    		    'music-kaijiang');  //开奖音效
					    	}
					    }
					});
				}
				kaiJianFunc();
			},
			//获取上期开奖期数
			getPrevLottery : function (_obj){
				var _prev = '';
				if(_obj.lottery_id == 12){		//pk10
					_prev = +_obj.lottery_no -1;
				}else{
					var lotteryNum = +$('#lottery-num').html();	//总期数
					var currLottery = _obj.lottery_no.split('-')[1];	//当前期数
					var prevNum = (+currLottery-1) + "";
					var lotteryDate = _obj.lottery_date;		//当前期 日期
					if(prevNum<=0)//当前第一期
				    {
						lotteryDate = lotteryDate.replace(/-/g , '');
						prevNum =  lotteryNum;
						//时间减去一天
					    var date =new Date(lotteryDate.substring(0,4),
					    	lotteryDate.substring(4,6)-1,lotteryDate.substring(6,8));
					    date.setDate(date.getDate()-1);
                        lotteryDate=date.getFullYear()+(date.getMonth()<9?
						    "0"+(date.getMonth()+1):date.getMonth()+1 
								)+ (date.getDate()<10?("0"+date.getDate()):date.getDate());
				 	}
					var fillZeroNum = (currLottery.length - prevNum.length);
					var _zero = '';
					for(var i=0;i<fillZeroNum;i++){
						_zero += '0';
					}
					prevNum = _zero + prevNum;
		
					lotteryDate = lotteryDate.replace(/-/g , '');
					_prev = lotteryDate + '-' +prevNum;
				}
				return _prev;
			},
			//倒计时 无限次循环
			__downTime : function (_obj){
				var _this = this;
				var _lotteryDate = _obj.lottery_time.split(' ')[0];
				var _lotteryTime = _obj.lottery_time.split(' ')[1];
				var _date = _lotteryDate.split('-');
				var _time = _lotteryTime.split(':');
				var _currTime = new Date(_obj.curr_time);
				Play.initDownTime(_currTime , {
					year : _date[0] ,
					month : _date[1],
					day : _date[2],
					hour : _time[0],
					min : _time[1],
					sec : _time[2]
				} , function (diffSecs){
					if(5 == diffSecs){
			            _this.playVoice(window.basePath+
			            	'static/media/stop-time.mp3' ,
			                'music-stoptime');  //停止售奖音效
			        }else if(0 >= diffSecs){
			        	$('#countdown_dashboard').stopCountDown();
			        	//停止 定时load开奖监控
			        	clearTimeout($.data($('.kj-hao')[0],'kaijiang_timer'));
						$('.digit').html('0');
			        	var _prevLottery = $('[data-id="sale-nper"]:eq(0)').html();
			        	var reWork = function (){$.none_alert(function (){
			        		_this.isTimeDistance(false);	//检查是否在间隔时间内
			        		$.alert({
			                   status    : 'warn',
			                   basicTitle  : '第 '+_prevLottery+' 期投注已截止！',
			                   bigContents : ['&nbsp;&nbsp;&nbsp;\
			                   	清空预投注内容请点击"确定"，\
			                   	不刷新页面请点击"取消"。'],
			                   buttons   : [
			                        {flag : 'ok' , name : '确定' , handler : function (){
				                       $.none_alert();
				                       $('#clear-cart').trigger('click');
				                       Play.reset();
				                       return false;
			                        }},{flag : 'cancel' , name : '关闭' , handler : function (){
				                       $.none_alert();
				                       return false;
			                        }}
			                    ]
			                });
			        	});};
			        	window.setTimeout(reWork , 1000);
			        	Play.lotteryHistory();
			        }
				});
			},
			//开奖引擎
			engine : function (_callBack){
				var _this = this;
				$.ajax({
					url 	: CGI.LOTTERY_TIME(),
					method 	: 'GET',
					data 	: "lotteryId="+
						$('#lottery-id').val(),
					success : function(data) {
						if (0 == data.retcode) {
							var _obj = data.data;
							$('[data-id="sale-nper"]').html(_obj.lottery_no);
							$('#stop-time').html(_obj.lottery_time);
							_this.__downTime(_obj);
							_callBack && _callBack(_obj);
						}else{
							$.exception(data.retcode,data.retmsg);
						}
					}
				});
			},
			init : function (){
				var _this = this;
				_this.isTimeDistance(true);	//检查是否在间隔时间内
			}
		},
		/**
		 * 最近十期投彩记录
		 */
		lotteryHistory : function (){
			$.ajax({
				url : CGI.LOTTERY_HISTORY(),
				method : 'GET',
				success : function(data) {
					if (0 == data.retcode) {
						var _html = _.template($(
							'#history-template').html(), {
							items : data.data
						});
						$('#play-history').html(_html);
						if(data.data.length ==0){
							$('#history-data').html($(
								'#history-empty-template').html());
							return;
						}
						$('#history-data tr').removeClass('alt');
						$('#history-data tr:odd').addClass('alt');
					}
				}
			});
		},
		/**
		 * 获得追号期数和追号总金额
		 */
		 calcAppendNoAndMoney : function (_money){
 			var count 			= 0;
     		var sppendbet_arr 	= [];
     		var money 			= 0;
     		$('#appendbet_table [data-flag="tr"]').removeClass('alt');
     		$('#appendbet_table [data-flag="tr"]:odd').addClass('alt');
     		$('[name="sppendbet"]').each(function (i , ele){
     			var _parent = $(ele).parent().parent();
     			if(ele.checked){
     				count ++;
     				_parent.fadeTo(50,1);
     				sppendbet_arr.push({
     					id : ele.value,
     					lotteryNo : _parent.find(
     						'[data-flag="sppend-lotteryNo"]').html(),
     					times : _parent.find(
     						'[data-flag="times"]').val() , 
     					money : _money
     				});
     			}else{
     				_parent.fadeTo(50,.5);
     			}
     		});
     		for(var i =0;i<sppendbet_arr.length;i++){
     			money += (+sppendbet_arr[i]['times']) * 
     				(+sppendbet_arr[i]['money']);
     		}

     		$('#append_total').html(count);
     		$('#append_total_money').html(money.toFixed(2));
 		},
 		// 查询历史开奖数据
 		queryHistoryLotteryData:function()
 		{
 			$.ajax({ 
			    url: CGI.LOTTERY_HISTORY_DATA(), 
			    dataType: 'json', 
			    data: "lotteryId="+$('#lottery-id').val(),
			    contentType: 'application/json',
			    success: function(data) {
			    	$.alert({
						isIcon : false,
						width : 600,
						isTable : true,
						title : ($('#historyLotteryDataDiv').attr("lotteryName")+'-历史开奖数据'),
						bigContents : [$('#history-table-template').html().replace('%content%' ,
							_.template('<%_.each(items,function (item , i){%>\
								<tr data-flag="tr" style="filter:alpha(opacity=40);-moz-opacity:0.4;opacity:0.4;">\
									<td><%=i+1%></td>\
									<td><%=item.lotteryMatches%></td>\
									<td><%=item.lotteryData%></td>\
									<td><%=item.lotteryTime%></td>\
								<tr>\
							<%})%>',{items:data.data}))] 
					});
			 
			    }
			});
 		}
	};

	/**
	 * 根据groupid查询所有玩法
	 */
	var getPlaysByGroupId = function(_groupId) {
		var deferred = $.Deferred();
		var dataStr = $.substitute('groupId={groupId}', 
			{groupId : _groupId});
		$.ajax({
			url : CGI.GET_PLAYS(),
			method : 'GET',
			data : dataStr,
			success : function(data) {
				if (0 == data.retcode) {
					play_arr = data.data; // 将玩法所有数据装入内存
					var _html = _.template($(
						'#paly-template').html(), {
						items : data.data
					});
					$('#play-menus').html(_html);
					deferred.resolve(); // 改变deferred对象的执行状态
				} else {
					$.exception(data.retcode , data.retmsg);
				}
			}
		});
		return deferred.promise(); // 返回promise对象
	};

	/**
	 * 获取当前玩法具体信息
	 */
	var getPlayByInfo = function() {
		var deferred = $.Deferred(), 
			_play_id = $('#play-menus .current').
				attr('data-value') || '', 
			i = 0, 
			playArrLen = play_arr.length;

		var eventListener = function (signal , _callback){
			var ss_timer = window.setInterval(function (){
				if(signal == 'yes'){
					window.clearInterval(ss_timer),ss_timer=null;
					signal = '';
					_callback && _callback();
				}
			},10);
		};

		for (; i < playArrLen; i++) {
			if (_play_id == play_arr[i]['id']) {
				curr_play_obj = play_arr[i]; // 将当前玩法存储
				$('#example').html(play_arr[i]['example']);
				$('#info').html(play_arr[i]['info'] || '');
				$('#simpleInfo').html(play_arr[i]['simpleInfo']);
				$('#playBonus').html(play_arr[i]['bonusProp']);

				var _conf = playsConf(play_arr[i]);
				var _tplName = _conf['template'];
				var _codeList = _conf['code_list'];
				var _html_obj = $.extend({items : _codeList} , _conf);
				var _html = _.template($('#' + _tplName).html(), _html_obj);
				$('#game-panel').html(_html);
				var isDel = false;
				var signal = '';	//信号



				//监听键盘删除操作 如果用户是按的删除键，就不将当前的玩法值设置进输入框中了
				$('#game-input').detach('keydown').on('keydown' , function (evt){
					var _this = this;
					window.setTimeout(function (){
						signal = 'yes';
						isDel = (evt.keyCode == 8 || evt.keyCode == 46) ? true : false;
						Play.getNumAndDetail(evt,true);
					},0);
				});
				//如果是IE11
				if((/Trident\/7\./).test(navigator.userAgent)){
					var _handler = function (evt){
						window.setTimeout(function (){
							
								eventListener(signal , function (){
									if(!isDel){
										evt = (evt) ? evt : window.event;
										Play.getNumAndDetail(evt);
									}
								});
							
						},0);
					};
					document.getElementById('game-input') && (function (){
						document.getElementById('game-input').
							removeEventListener('DOMAttrModified' , _handler,false);
						document.getElementById('game-input').
							addEventListener('DOMAttrModified' , _handler,false);
					})();
				}else{ //其他浏览器
					//输入监控事件
					$('#game-input').detach('input propertychange').
						on('input propertychange' , function (evt){
						var _this = this;
						window.setTimeout(function (){
							
								eventListener(signal , function (){
									if(!isDel){
										evt = (evt) ? evt : window.event;
										Play.getNumAndDetail(evt);
									}
								});
							
						},0);
					});
				}
				//初始化输入型的位置选择
				if(_conf['isPosition']){
					var _p_arr = _conf['param'][2];
					_p_arr && (function (){
						for(var i = 0; i < _p_arr.length ;i++){
							$('#position_' + _p_arr[i]).
								attr('checked' , true);
						}
						Play.getPlan(_p_arr.length);
						Play.getNumAndDetail();
					})();
				}
				break;
			}
		}
		deferred.resolve(); // 改变deferred对象的执行状态
		return deferred.promise(); // 返回promise对象
	};
	
	/**
	 * 事件绑定
	 */
	var bindEvent = function() {
		$('#play-group-menus').delegate('li', 'click', function(e) {
			$(e.delegateTarget).find('li').removeClass('current');
			$(this).addClass('current');
			// 玩法组点击事件触发的条件
			getPlaysByGroupId($(this).attr('data-value')).
				then(getPlayByInfo).then(Play.reset);
		});
		$('#play-menus').delegate('li', 'click', function(e) {
			$(e.delegateTarget).find('li').removeClass('current');
			$(this).addClass('current');
			getPlayByInfo().then(Play.reset);
		});

		// 数字按钮点击事件
		$('.game-xhlist').delegate('.game-lbtn','click',function (){
			var _name = curr_play_obj['ruleFun'].split('_')[1];
			if('zuxbd' == _name){	//是组选包胆系列 就启用单选逻辑 
				$('.game-xhlist .game-lbtn').
					removeClass('game-lbtn-active');
				$(this).addClass('game-lbtn-active');
			}else{					//非组选包胆系列就启用点选逻辑
				if ($(this).hasClass('game-lbtn-active')) {
					$(this).removeClass('game-lbtn-active');
				} else {
					//控制不能选择相同数字 GusonYang
					if(playsConf(curr_play_obj)['isOpposite']){
						var _this = $(this);
						var _idx = _this.parent().find('input').index(_this);
						$('#game-panel .game-xhlist-left').each(function(){
							$("input",this).eq(_idx).
								removeClass('game-lbtn-active');
						});
					}
					$(this).addClass('game-lbtn-active');
				}
			}
			Play.getNumAndDetail();
		});
		
		//模式点击事件
		$('input[name="model"]').click(function() {
			if('input'==playsConf(curr_play_obj)['type']){
				Play.getNumAndDetail.apply(null,
					['input',playsConf(curr_play_obj)['param']]);
			}else{
				Play.getNumAndDetail();
			}
		});

		// 倍数 - 点击事件
		$('.minus').click(function() {
			var _times = +$('.pro-qty-int').val();
			if (!_times)
				_times = 1;
			_times--;
			if (_times <= 1) {
				$('.pro-qty-int').val(1);
			} else {
				$('.pro-qty-int').val(_times);
			}
			if('input'==playsConf(curr_play_obj)['type']){
				Play.getNumAndDetail.apply(null,
					['input',playsConf(curr_play_obj)['param']]);
			}else{
				Play.getNumAndDetail();
			}
		});

		// 倍数 + 点击事件
		$('.plus').click(function() {
			var _times = +$('.pro-qty-int').val();
			if (!_times)
				_times = 1;
			_times++;
			$('.pro-qty-int').val(_times);
			if('input'==playsConf(curr_play_obj)['type']){
				Play.getNumAndDetail.apply(null,
					['input',playsConf(curr_play_obj)['param']]);
			}else{
				Play.getNumAndDetail();
			}
		});
		//倍数输入框输入事件
		$('.pro-qty-int').bind('input property' , function (){
			if(/^\d+$/.test($(this).val())){
				if('input'==playsConf(curr_play_obj)['type']){
					Play.getNumAndDetail.apply(null,
						['input',playsConf(curr_play_obj)['param']]);
				}else{
					Play.getNumAndDetail();
				}
			}else{
				$.alert({
					status     : 'error',
					basicTitle : '数字非法'
				});
				$('.pro-qty-int').val(1);
			}
		});
	
		//获取位置和方案
		$("#delegate-content").delegate('input[name^="position"]', 'click' , function (){
			Play.getPlan(playsConf(curr_play_obj)['param'][2].length);
			Play.getNumAndDetail();
		});
		// 给右侧按钮绑定事件
		Play.rightBtn();
		
		//添加投注
		$("#delegate-content").delegate('#add-touzhu', 'click' , function (){
			var isFanAn = ('none' !== $('span[data-flag="position_area"]').css('display')) ? true : false;
			var _check_arr = [];
			if(isFanAn){
				var pos_conf = {'0' : '万' , '1' : '千' , '2' : '百' , '3' : '十' , '4' : '个'};
				$('input[name="position"]:checked').each(function (index , ele){
					_check_arr.push(pos_conf[ele.getAttribute('value')]);
				});
			}
			//向购物车推送投注数据
			Play.cart({
				orderNo : Play.createCustomOrderNo(),		//创建自定义单号
				groupid : curr_play_obj['lottery_groupId'],	//玩法组id
				playid 	: curr_play_obj['id'],				//玩法id
				playName: 	curr_play_obj['name'],			//玩法名称
				zhu 	: Play.parsing(),					//投注明细
				total 	: $('#zhu').html(),					//投注总数
				money 	: $('#money').html(),				//投注金额
				times 	: $('.pro-qty-int').val(),			//倍数
				model 	: $.modelToCHN($('input[name="model"]:checked').val()),//模式
				model_c : $('input[name="model"]:checked').val(),	//模式(用来存储数据的)
				bonus 	: $('#playBonus').html() + '-' + $('#playBonusPercent').html(),	//奖金-返点
				bonus_c	: $.trim($('#playBonus').html()),			//奖金(用来存储数据的)
				fandian : $('#playBonusPercent').html(),		//返点(用来存储数据的)
				fangAn 	: _check_arr.join(",")					//方案
			});
			$('.pro-qty-int').val('1');
			Play.reset();
		});
		
		//-----鼠标移入高亮 start ----
		$("#delegate-content").delegate('#cart-list tr,#history-data tr', 'mouseover' , function (){
			$(this).addClass('over');
		});
		$("#delegate-content").delegate('#cart-list tr,#history-data tr', 'mouseout' , function (){
			$(this).removeClass('over');
		});
		//----鼠标移入高亮 end ---
		
		//购物车-删除单项 按钮点击事件
		$("#delegate-content").delegate('.ico-delete', 'click' , function (){
			$(this).parents('tr').fadeOut('slow' , function (){
				if($(this).attr('sub_orderNo') == undefined){
					var mainOrderNo = $(this).attr('data-orderNo');
					$('[sub_orderNo="'+mainOrderNo+'"]').remove();
				}
				$(this).remove();
				if($('#cart-list tr').length <= 0) 
					$('#cart-list').html($('#cart-empty-template').html());
				Play.cartMonitor();	//购物车监控
			});
		});
		//清空购物车所有投注号码
		$("#delegate-content").delegate('#clear-cart', 'click' , function (){
			$('#cart-list tr').fadeOut('slow' , function (){
				$('#cart-list').html($('#cart-empty-template').html());
				Play.cartMonitor();	//购物车监控
			});
		});

		$('#cart-list').html($('#cart-empty-template').html());
		var touZhuFunc = function (){
			var _data_arr = Play.cartData();
			var data = JSON.stringify(_data_arr);
			if(_data_arr.length ==0){
				$.alert({
		    		status : 'error',
					basicTitle : '无投注数据不能提交！'
				});
				return;
			}
			$.ajax({
				url 	: CGI.LOTTERY_DISTANCE(),
				method 	: 'GET',
				data 	: "lotteryId="+$('#lottery-id').val(),
				success : function(disData){
					if (0 == disData.retcode && disData.data.length > 0) {
						$.alert({
				    		status : 'error',
				    		width  : 600,
							basicTitle : $('[data-id="sale-nper"]:eq(0)').html()+
								"已过销售期，请您购买下一期。"//'封单时间不能提交投注！'
						});
						return;
					}
					var _cartData = Play.cartData();
					if(_cartData.length > 3 ){
						_cartData.length = 4;
					};
					$.alert({
			    		status : 'help',
			    		title  : '投注提示',
			    		width  : 500,
						basicTitle : '确定要购买第'+
							$('[data-id="sale-nper"]:eq(0)').html()+
							'期的彩票？',
						bigContents: [$(
							'#confirmTouzhu-table-template').
							html().replace('%content%' , _.template($(
								'#confirmTouzhu-table-tbody-template').
							html() , {items : _cartData})),'','',
						'总投注数 : <em>'+$('#cart-total-zhu').
							html()+'</em> 注 | 购买金额 : '+ 
							$('#cart-total-money').html() + '元'],
						buttons : [{'flag' : 'ok' , 
						'name' : '确定购买' , 'handler' : function (){
							$('[data-flag="ok"]').attr("disable","true");
							$.ajax({ 
							    url: CGI.SUBMIT_CODES(), 
							    type: 'POST', 
							    dataType: 'json', 
							    data: data, 
							    contentType: 'application/json',
							    success: function(data) {
							    	var retcode = data.retcode;
							    	if(retcode!="0")
							    	{
							    		$.none_alert(function()
							    		{
							    			return $.alert({
									    		status : 'error',
												basicTitle : retcode
											});
							    		}		
							    		);
							    	    return;
							    	}
							    	$('#clear-cart').trigger('click');
							    	$.none_alert(function (){
								    	$.alert({
								    		status : 'ok',
											basicTitle : '提交成功！'
										});
									});
							    	Play.lotteryHistory();
									reloadUserInfo();
							    }
							});
						}},{'flag' : 'cancel' , 'name' : '取消购买' , 'handler' : function (){
							$.none_alert();
						}}]
					});
				}
			});
			return false;
		};

		//投注
		$("#delegate-content").delegate('#btn-touzhu', 'click' , touZhuFunc);
		
		//追号
		$("#delegate-content").delegate('#btn-zhuihao', 'click' , function (){
			if($('#cart-list tr').length == 1 && 
			   $('#cart-list tr:eq(0)').attr('data-flag') == 'empty'){
				$.alert({
		    		status : 'error',
					basicTitle : '请先添加投注内容！'
				});
				return;
			}
			if($('#cart-list tr').length > 1){
				$.alert({
		    		status : 'warn',
					basicTitle : '只能针对一个方案发起追号！'
				});
				return;
			}
			var _money = $('#cart-list tr:eq(0) [data-flag="money"]').val();
			var _times = $('#cart-list tr:eq(0) [data-flag="times"]').val();

			$.ajax({ 
			    url: CGI.LOTTERY_APPENDBET(), 
			    dataType: 'json', 
			    data: "lotteryId="+$('#lottery-id').val()+
			    "&lotteryNo="+$('[data-id="sale-nper"]:eq(0)').html(), 
			    contentType: 'application/json',
			    success: function(data) {
			    	$.alert({
						isIcon : false,
						width : 600,
						isTable : true,
						title : '<input type="checkbox" checked id="stop-append" /> 中奖后停止追号 追号期数:<em id="append_total">0</em> 总金额：<em id="append_total_money">0.00</em>元',
						bigContents : [$('#appendbet-table-template').html().replace('%content%' ,
							_.template('<%_.each(items,function (item , i){%>\
								<tr data-flag="tr" style="filter:alpha(opacity=40);-moz-opacity:0.4;opacity:0.4;">\
									<td><input type="checkbox" name="sppendbet" value="<%=item.id%>"/>&nbsp;&nbsp;<span data-flag="sppend-lotteryNo"><%=item.lotteryMatches%></span></td>\
									<td><input data-flag="times" type="input" value="'+_times+'"/></td>\
									<td>'+_money+'元</td>\
									<td><%=item.lotteryTime%></td>\
								<tr>\
							<%})%>',{items:data.data}))],
						buttons : [
						    {flag : 'quanxuan' , name : '全选' , handler : function (){
								$('#appendbet_lottery_no')[0].checked = true;
								$('[name="sppendbet"]').each(function (i,ele){
									ele.checked = true;
								});
							}},
							{flag : 'fanxuan' , name : '反选' , handler : function (){
								$('#appendbet_lottery_no')[0].checked = false;
								$('[name="sppendbet"]').each(function (i,ele){
									if(ele.checked){
										ele.checked = false;
									}else{
										ele.checked = true;
									}
								});
							}},
							{flag : 'ok_zhuihao' , name : '确定追号' , handler : function (){
								var bets_zhuiHaoMode = $('#stop-append').is(":checked") ? 1 : 0;
								var _firstTr = $('#cart-list tr').first();
								var _orderNo = _firstTr.attr('data-orderNo');
								$('#appendbet-table-tbody tr').each(function(){
									var _this = $(this);
									if($('input[name="sppendbet"]',_this).is(":checked")){
										var newBet = _firstTr.clone();
										var lotteryNo = $('[data-flag="sppend-lotteryNo"]',_this).html();
										var times = $('[data-flag="times"]',_this).val();
										var money = parseFloat($('[data-flag="money"]',newBet).val())/parseInt($('[data-flag="times"]',newBet).val())*parseInt(times);
										
										var lntr = $('.lotteryNo', newBet).html(lotteryNo+
											'<input type="hidden" data-flag="lotteryNo" value="'+lotteryNo+'">');
										lntr.attr('bets_zhuiHao', '1');
										lntr.attr('bets_zhuiHaoMode', bets_zhuiHaoMode);
										lntr.attr('bets_srcOrder', 
											$('[data-flag="lotteryNo"]', $('#cart-list tr').first()).val());
										
										$('.times', newBet).html(times+
											'倍<input type="hidden" data-flag="times" value="'+times+'">');
										$('.money', newBet).html(money.toFixed(2)+
											'元<input type="hidden" data-flag="money" value="'+money+'">');
										newBet.attr('sub_orderNo' , _orderNo);
										newBet.attr('data-orderNo' , Play.createCustomOrderNo());
										$('#cart-list').append(newBet);
									}
								});
								Play.cartMonitor();	//购物车监控
								$.none_alert();
								return false;
							}},
							{flag : 'cancel_zhuihao' , name : '取消追号' , handler : function (){
								$.none_alert();
								return false;
							}}
						]
					});
			    	$('#appendbet_lottery_no').click(function (){
			    		if(this.checked){
			    			$('[name="sppendbet"]').each(function (i,ele){
								ele.checked = true;
							});
			    		}else{
			    			$('[name="sppendbet"]').each(function (i,ele){
								ele.checked = false;
							});
			    		}
			    	});
			    	
			    	//给复选框、全选、反选按钮绑定点击事件
			    	$('#appendbet_lottery_no,\
			    		[data-flag="quanxuan"],\
			    		[data-flag="fanxuan"],\
			    		[name="sppendbet"]').click(function (){
			    		Play.calcAppendNoAndMoney(_money);
			    	});
			    	//给倍数输入框绑定键盘按下事件
			    	$('#appendbet-table-tbody \
			    		[data-flag="times"]').keydown(function (){
			    		var _this = $(this);
			    		window.setTimeout(function (){
			    			var _val = _this.val();
			    			if(!/^\d+$/.test(_val)){
			    				_this.val(_val.replace(/\D/g,''));
			    				alert("只能输入数字！");
			    				return;
			    			}
			    			Play.calcAppendNoAndMoney(_money);
			    		},0);
			    	});
			    }
			});
			return false;
		});

		//点击购物车项时弹出提示框
		$("#delegate-content").
			delegate('tr[data-flag="cart-item"]', 
				'click' , function (e){
			var _this = $(this);
			if(!$(e.target).hasClass('ico-delete')){
				$.alert({
					isIcon : false,
					title : '投注项详情',
						bigContents : [
		               '玩法：'+ $('[data-flag="playName"]').val(),
		               '模式：'+$.modelToCHN(_this.find('[data-flag="model"]').val())+'模式',
		               '奖金：'+_this.find('[data-flag="bonus_c"]').val(),
		               '返点: '+_this.find('[data-flag="fandian"]').val(),
		               '包含 '+_this.find('[data-flag="total"]').val()+
		               ' 注，'+_this.find('[data-flag="times"]').val()+
		               '倍，共计'+_this.find('[data-flag="money"]').val()+
		               '元'
		            ],
					smallTitle : '完整投注内容',
					smallContents : [_this.find('[data-flag="zhu"]').val()]
				});
			}
			return false;
		});
		
		//游戏记录详情
		$("#delegate-content").delegate('#history-data tr', 'click' , function (e){
			var _this = $(this);
			if($(e.target).attr('data-flag') != 'cancel_order'){
				$.ajax({ 
				    url: CGI.LOTTERY_BET_DETAIL(), 
				    dataType: 'json', 
				    data: "id="+$('.bets_order', _this).attr('data-id'), 
				    contentType: 'application/json',
				    success: function(data) {
				    	var ms; 
			    		if(data.bets_mode == 2.00){
			    			ms = '元'
			    		}else if(data.bets_mode == 0.20){
			    			ms = '角'
			    		}else{
			    			ms = '分'
			    		}
				    	$.alert({
							isIcon : false,
							title : '订单详情',
							bigContents : [
							   '投注用户：'+ data.uname,
							   '彩种：'+ data.lottery_name,
							   '玩法：'+ data.play_name,
							   '订单状态：'+ data.betsStatus,
							   '订单编号：'+ data.bets_order,
							   '购买模式：'+ ms ,
							   '奖金返点：'+ data.bets_bonusProp+'－'+data.bets_fanDian+'%' ,
							   '开奖号码：'+ (data.bets_lotteryNo || ''),
							   '投注时间：'+ moment(data.bets_time).format('YYYY-MM-DD HH:mm:ss'),
							   '投注期号：'+ data.lottery_no,
							   '购买倍数：'+ data.bets_beiShu,
							   '开奖时间：'+ (data.bets_kjTime?moment(data.bets_kjTime).format('YYYY-MM-DD HH:mm:ss'):''),
							   '购买金额：'+ (data.bets_amount || '0')+'元',
							   '返点金额：'+ (data.bets_fanDianAmount || '0')+'元',
							   '中奖注数：'+ (data.bets_zjCount || '0'),
							   '中奖金额：'+ (data.bets_bonus || '0')+'元',
							   '购买盈亏：'+ (data.bets_lotteryNo ? (data.bets_bonus - data.bets_amount + data.bets_fanDianAmount).toFixed(4) : '0')+'元'
				            ],
							smallTitle : '完整投注内容',
							smallContents : [data.bets_data],
							column: 3,
							column_width: 200,
							width: 600
						});
				    }
				});
			}
			return false;
		});
		
		/**
		 * 滑块控制(奖金/返点计算)
		 */
		$("#blue").slider({
			orientation: "horizontal",
			range: "min",
			max :(fandian + 0.01),
			value: 0,
			step:0.1,
			slide : Play.slider
		});
		//撤单点击事件
		$("#delegate-content").delegate(
			'[data-flag="cancel_order"]', 'click' , function (){
			var _this = this;
	    	$.alert({
	    		status : 'help',
				basicTitle : '您确定要撤单？',
				buttons : [{'flag' : 'ok' , 'name' : '确定' , 'handler' : function(){
					$('#history-data tr').removeClass('alt');
					$('#history-data tr:odd').addClass('alt');
					$.ajax({ 
					    url: CGI.CANCEL_ORDER(), 
					    dataType: 'json', 
					    data: "lotteryId="+$('#lottery-id').val() +
					    	"&lotteryBetsId="+$(_this).parents('tr').find(
					    		'[data-flag="bets_order"]').attr('data-id'), 
					    contentType: 'application/json',
					    success: function(data) {
					    	if(data.retcode ===0){
					    		Play.lotteryHistory();
					    		$.none_alert(function()
					    		{
					    			$.alert({
			    			    		status : 'ok',
			    						basicTitle : '撤单成功！'
			    					});
					    			reloadUserInfo();
					    		}		
					    		);
					    	}else{
					    		$.exception(data.retcode , data.retmsg);
					    	}
					    }
					});
				}},{'flag' : 'cancel' , 'name' : '取消' , 'handler' : function (){
					$.none_alert();
				}}]
			});
		});
		$('#voice').click(function (){
			var musicVal = $.cookie('LH_02_MUSIC_VOICE');
			$.removeCookie('LH_02_MUSIC_VOICE');
			if('0' === musicVal){
				$(this).removeClass('voice-off');
				$(this).addClass('voice-on');
				
				//$('#voice').attr('title' , '点击关闭声音');
				$.cookie('LH_02_MUSIC_VOICE', '1', { expires: 7 });
			}else{
				$(this).removeClass('voice-on');
				$(this).addClass('voice-off');
				if(navigator.userAgent.indexOf('MSIE') >= 0){
					$('bgsound').remove();
				}else{
					$('audio').remove();
				}
				//$('#voice').attr('title' , '点击开启声音');
				$.cookie('LH_02_MUSIC_VOICE', '0', { expires: 7 });
			}
		});
		
		$('#historyLotteryDataDiv').click(function(e) {
		      Play.queryHistoryLotteryData();
		});
	};
	//清空按钮触发事件
	$("#delegate-content").delegate('#input-clear', 'click' , function (){
		$('#game-input').val('');
		Play.getNumAndDetail();
	});
	
	if('0' === $.cookie('LH_02_MUSIC_VOICE')){
		$('#voice').removeClass('voice-on');
		$('#voice').addClass('voice-off');
		//$('#voice').attr('title' , '点击开启声音');
	}else{
		$('#voice').removeClass('voice-off');
		$('#voice').addClass('voice-on');
		//$('#voice').attr('title' , '点击关闭声音');
	}
	


	$(function(){
		getPlaysByGroupId($('#play-group-menus li').first().attr('data-value'))
		.then(getPlayByInfo).then(function (){}).then(Play.slider).then(bindEvent);
		Play.prize.init();
		Play.lotteryHistory();
	});
})(window);